package model.beans;

import core.Database;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.io.Serializable;
import java.sql.*;
import org.apache.log4j.Logger;

/**
 *
 * @author Danon
 */
@ManagedBean @RequestScoped
public class LinkBean implements Serializable {
    public final long serialVersionID = 1L;
    private static final Logger logger = Logger.getLogger(LinkBean.class);
    
    private int id;
    private String title;
    private float bandwidth;
    private RouterBean router1, router2;

    public float getCurrentBandwidth() {
//  select nvl(sum(q.bandwidth), 0) as engaged
//  from (
//      select o.bandwidth as bandwidth
//      from engagements e, orders o
//      where o.order_id = e.order_id and e.link_id = 6568
//  ) q;
        
        float engaged = 0;
        try {
            Connection c = Database.getInstance().getConnection();
            try (PreparedStatement ps = c.prepareStatement("select nvl(sum(q.bandwidth), 0) as engaged "
                         + "from (select o.bandwidth as bandwidth "
                         + "from engagements e, orders o "
                         + "where o.order_id = e.order_id and e.link_id = ?) q")) {
                ps.setInt(1, getId());
                ResultSet rs = ps.executeQuery();
                if(rs.next()) {
                    engaged = rs.getFloat("engaged");
                }
                rs.close();
            }
        } catch (Exception ex) { 
            logger.debug(ex.getMessage()); 
        }
        return bandwidth - engaged;
    }

    public LinkBean() {
        
    }
    
    public LinkBean(int id, String title, float bandwidth) {
        this.id = id;
        this.title = title;
        this.bandwidth = bandwidth;
    }

    public RouterBean getRouter1() {
        return router1;
    }

    public void setRouter1(RouterBean router1) {
        this.router1 = router1;
    }

    public RouterBean getRouter2() {
        return router2;
    }

    public void setRouter2(RouterBean router2) {
        this.router2 = router2;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public float getBandwidth() {
        return bandwidth;
    }

    public void setBandwidth(float bandwidth) {
        this.bandwidth = bandwidth;
    }
    
    @Override
    public String toString() {
        return "Link{name:" + title + "; id:"+id+"; bandwidth:"+bandwidth+"}";
    }

}